package com.gege;

import java.util.concurrent.*;

/**
 * 使用 CyclicBarrier
 * <p>
 * CyclicBarrier 是基于 Condition 的
 *
 * @author gechenpeng
 * @date 2021-04-13
 */
public class Demo6 {

    public static void main(String[] args) throws Exception {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1024),
                new ThreadPoolExecutor.CallerRunsPolicy());

        long start = System.currentTimeMillis();

        Future<String> future = executorService.submit(() -> {
            try {
                return execute();
            } finally {
                try {
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();

        cyclicBarrier.await();

        String message = future.get();

        System.out.println("线程运行的结果是: " + message + ", 耗时: " +
                (System.currentTimeMillis() - start) + " ms");
    }

    private static String execute() throws Exception {
        Thread.sleep(5000);
        return "ok";
    }
}
